package by.demchenko.sample.webapp.page.home.share;

import by.demchenko.sample.datamodel.Account;
import by.demchenko.sample.datamodel.Faculty;
import by.demchenko.sample.datamodel.Person;
import by.demchenko.sample.datamodel.enums.Gender;
import by.demchenko.sample.datamodel.enums.UserType;
import by.demchenko.sample.services.FacultyService;
import by.demchenko.sample.services.PersonService;
import by.demchenko.sample.services.UserService;
import by.demchenko.sample.webapp.page.admin.StudentsPage;
import by.demchenko.sample.webapp.page.home.BaseLayout;
import org.apache.wicket.Page;
import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.extensions.markup.html.captcha.CaptchaImageResource;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.util.value.ValueMap;
import org.apache.wicket.validation.validator.EmailAddressValidator;

import javax.inject.Inject;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class CreateAccountPage extends BaseLayout {
    @Inject
    private PersonService personService;

    @Inject
    private UserService userService;

    @Inject
    private FacultyService facultyService;

    private String imagePass;
    private final ValueMap properties = new ValueMap();
    private CaptchaImageResource captchaImageResource;

    public CreateAccountPage() {

    }

    private static int randomInt(int min, int max) {
        return (int) (Math.random() * (max - min) + min);
    }

    private static String randomString(int min, int max) {
        int num = randomInt(min, max);
        byte b[] = new byte[num];
        for (int i = 0; i < num; i++)
            b[i] = (byte) randomInt('A', 'Z');
        return new String(b);
    }

    private String getPassword()
    {
        return properties.getString("password");
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        //add(new Label("headerTitle", "Редактирование"));
        //add(new Label("subtitle", "Редктирование"));
        add(new FeedbackPanel("feedback"));

        //Form<Person> form = new Form<>("form", new CompoundPropertyModel<>(student));
        Form<Person> form = new Form<>("form");

        Person student = new Person();

        final TextField<String> tfFirstName = new TextField<>("firstName", new PropertyModel<>(student, "firstName"));
        tfFirstName.add(new PropertyValidator<>());
        tfFirstName.setLabel(new ResourceModel("person.firstName"));
        form.add(tfFirstName);

        final TextField<String> tfLastName = new TextField<>("lastName", new PropertyModel<>(student, "lastName"));
        tfLastName.add(new PropertyValidator<>());
        tfLastName.setLabel(new ResourceModel("person.lastName"));
        form.add(tfLastName);

        final TextField<String> tfMiddleName = new TextField<>("middleName", new PropertyModel<>(student, "middleName"));
        tfMiddleName.add(new PropertyValidator<>());
        tfMiddleName.setLabel(new ResourceModel("person.middleName"));
        form.add(tfMiddleName);

        List<Faculty> facultyList = facultyService.getAll();
        final DropDownChoice<Faculty> tfFaculty = new DropDownChoice<>(
                "faculty",
                new PropertyModel<>(student, "faculty"),
                facultyList,
                new ChoiceRenderer<>("name", "id"));
        tfFaculty.setLabel(new ResourceModel("person.faculty"));
        tfFaculty.setRequired(true);
        form.add(tfFaculty);

        final TextField<Date> tfDateOfBirth = new TextField<>("dateOfBirth", new PropertyModel<>(student, "dateOfBirth"));
        tfDateOfBirth.add(new PropertyValidator<>());
        form.add(tfDateOfBirth);

        final DropDownChoice<Gender> tfGender = new DropDownChoice<Gender>(
                "gender",
                new PropertyModel<>(student, "gender"),
                Arrays.asList(Gender.values()),
                new EnumChoiceRenderer<>(this));
        tfGender.add(new PropertyValidator<>());
        tfGender.setLabel(new ResourceModel("person.gender"));
        form.add(tfGender);

        final TextField<String> tfPhone = new TextField<>("phone", new PropertyModel<>(student, "phone"));
        tfPhone.add(new PropertyValidator<>());
        tfPhone.setLabel(new ResourceModel("person.phone"));
        form.add(tfPhone);

        Account newAccount = new Account();

        final TextField<String> tfLogin = new TextField<>("loginr", new PropertyModel<>(newAccount, "login"));
        //tfLogin.add(new PropertyValidator<>());
        UniqueLoginValidator uniqueLoginValidator = new UniqueLoginValidator();
        tfLogin.add(uniqueLoginValidator);
        tfLogin.setLabel(new ResourceModel("person.login"));
        form.add(tfLogin);

        final PasswordTextField tfPassword = new PasswordTextField("passwordr", new PropertyModel<>(newAccount, "password"));
        tfPassword.setResetPassword(true);
        tfPassword.add(new PropertyValidator<>());
        tfPassword.setLabel(new ResourceModel("person.password"));
        form.add(tfPassword);

        final TextField<String> tfEmail = new TextField<>("email", new PropertyModel<>(newAccount, "email"));
        tfEmail.add(EmailAddressValidator.getInstance());
        tfEmail.setLabel(new ResourceModel("person.email"));
        form.add(tfEmail);

        imagePass = randomString(4,5);
        captchaImageResource = new CaptchaImageResource(imagePass);
        //captchaImageResource.invalidate();

        form.add(new NonCachingImage("captchaImage", captchaImageResource));

        form.add(new RequiredTextField<String>("captcha", new PropertyModel<>(properties, "password")) {
            @Override
            protected final void onComponentTag(final ComponentTag tag) {
                super.onComponentTag(tag);
                tag.put("value", "");
            }
        });

        form.add(new SubmitLink("sumbit-link") {
            @Override
            public void onSubmit() {
                super.onSubmit();

                if (!imagePass.equals(getPassword()))
                {
                    error("Captcha is wrong!");
                    captchaImageResource.invalidate();
                    return;
                };

                captchaImageResource.invalidate();

                if (student.getId() != null) {
                    personService.saveOrUpdate(student);
                } else {
                    newAccount.setUserType(UserType.STUDENT);
                    //String md5Password = DigestUtils.md5DigestAsHex(acc.getPassword().getBytes());
                    //acc.setPassword(md5Password);
                    userService.createNewUser(student, newAccount);
                }

                CoursesPage page = new CoursesPage();
                setResponsePage(page);
            }

            @Override
            public void onError() {
                super.onError();
            }
        });

        form.add(new Link<Void>("back-link") {

            @Override
            public void onClick() {
                setResponsePage(new CoursesPage());
            }
        });

        add(form);
    }

}
